package com.liwen.project.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {


    @Value("${auth.whitelist:}")
    private String whiteList;


    private List<String> fixedList = Arrays.asList(
        new String[]{
            "/ssoLogin",
            "/error",
            "/orgTree/**",
            "/xxl-job/**",
            "/swagger/**",
            "/api-docs/**"
        });

    @Autowired
    private AuthInterceptor mtcAuthInterceptor;

    /**
     * 发现如果继承了WebMvcConfigurationSupport，则在yml中配置的相关内容会失效。 需要重新指定静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html", "doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> allWhite = new ArrayList<>();
        allWhite.addAll(this.fixedList);
        if (StringUtils.isNoneBlank(new CharSequence[]{this.whiteList})) {
            /*logger.info("过滤的url:{}", this.whiteList);*/
            List<String> configList = Arrays.asList(this.whiteList.split(","));
            allWhite.addAll(configList);
        }
        List<String> distinctList = (List<String>) allWhite.stream().distinct().collect(Collectors.toList());
        registry.addInterceptor((HandlerInterceptor) this.mtcAuthInterceptor).addPathPatterns(new String[]{"/**"})
            .excludePathPatterns(distinctList);
    }
}
